/**
 *  Zing News Code
 *  Version 2.37 (13/02/2014)
 */

// check if it's correct domain
var isEmbed = (window!=window.parent), Player;



$.ajaxSetup({
    timeout: 5000
});

// initial configuration
var APP_ID = '622829237762080';
var INITIAL_TIME = now();
var page = new Page();
if (!$.support.transition) $.fn.transition = $.fn.animate;

$(document).ready(function () {
    if ($.cookie) {
        $.cookie.json = true;
    }


    if ($(document).width() > 1200) {
        DEVICE.screen = "wide";
    } else {
        DEVICE.screen = "standard";
    }


    page.init();

    // // check if version cookie set, if yes, extend it for another day
    // var cookieMobile = $.cookie('znews_mobile');
    // if (cookieMobile != null) {
    //     $.cookie('znews_mobile', cookieMobile, {
    //         expires: 1,
    //         path: '/'
    //     });
    // }

    // if (page.getPageType() == 'home') {
    //     midPageDetector.attach();
    // }

    // if(window.location.hash.search('apptablet') >= 0 && DEVICE.platform=="ios") {
    //     window.location.href = "znews://action?act=doneLoading";
    // }
});

$(window).bind('load', function () {
    page.setupScrollbar('.scroll');
    page.slider.init();
    //page.ticker.init();
}).on('blur', function () {
    INITIAL_TIME = now();
});

// /**
//  * Check if user comeback after certain amount of time then reload the content
//  */
// if (page.getPageType() == 'home') {
//     $(window).on('focus', function () {
//         var time = Math.floor(( now() - INITIAL_TIME) / 60000);
//         //ga('send', 'event', 'Window', 'Refocus Interval',window.location.pathname, time);
//         if (time >= 15) {
//             //ga('send', 'event', 'Window', 'Auto Reloading', window.location.pathname, time);
//             window.location.reload(true);
//         }
//     });
// }

function Page() {
    var self = this;
    var cachedPageType;


    this.livestream = new LiveStream();
    //this.interview = new Interview();
    this.ticker = null;
    this.slider = new Slideshow('.pictures', 'article');
    this.article = new Article();
    this.comment = new SocialPlugin();
    this.storage = new Storage('local');
    this.navigationMenu;

    this.init = function () {

        Player = new VideoPlayer().init();
        self.setupTrackingLink();
        self.ticker = new NewsTicker($('.hotnews'), 'li');
        //self.renderSocialCount();

        if(DEVICE.type=="desktop") {
            //self.setupSamsungAds();
        }

        // self.setupSearchBox();
        self.article.init();

        self.navigationMenu = new NavigationMenu();
        self.navigationMenu.show();

        self.setupToolbox();
        self.comment.init();

        $('#top .parent').hover(function () {
            $(this).addClass('active');
        }, function () {
            $(this).removeClass('active');
        });

        // render article publish time
        var $timers = $('time');
        for (var i = 0, length = $timers.length; i < length; i++) {
            var $timer = $timers.eq(i),
                friendly = $timer.html() + page.formatTime($timer.attr('datetime'), {
                    friendly: $timer.hasClass('friendly')
                });

            $timer.html(friendly);
        };

        // initialize grid layout
        var $gridView = $('.gridview');
        if ($gridView.length > 0 && DEVICE.type == "desktop") {
            loadPlugin('isotope', 'isotope.1.5.25.js', function(){
                $gridView.isotope({
                    // options
                    itemSelector: 'article',
                    layoutMode: 'masonry',
                    transformsEnabled: false,
                    gutterWidth: 20
                });
            });

        }

        // setup category feed subscription dropdown box on homepage
        $('section.category .followbox').hover(
            function () {
                $(this).addClass('hovering');
            },
            function () {
                $(this).removeClass('hovering');
            }
        );

        // initialize live stream
        if ($('#livestream').length > 0 && $('#livestream .controller').length > 0) {
            page.livestream.init($('#livestream .controller').attr('data'));
        }

        // initialize live interview if status = live/question
        var $interviews = $('div[submit*="interview"]');
        $interviews.each(function(){
            (new Interview()).init(this,$(this).attr('data'),$(this).attr('submit'));
        });

        // showing pr articles in category page
        // var pageType = self.getPageType();
        // if (pageType === 'category') {
        //     var target = '.cate_content section.cate_content';
        //     if ($(target).length==0) {
        //         target = 'section.cate_content';
        //     }
        //     var $adsArticles = $(target+' article.advertising');
        //     if ($adsArticles.length > 0) {
        //         $articles = $(target+' article:not(.advertising)');

        //         var adsIndex = 0,
        //             adsLength = $adsArticles.length;

        //         for (var i = 0, length = $articles.length; i < length; i += 2) {
        //             if (adsIndex >= adsLength) {
        //                 break;
        //             }
        //             $adsArticles.eq(adsIndex).insertAfter($articles.eq(i)).show();
        //             ++adsIndex;
        //         }

        //         while (adsIndex < adsLength) {
        //             $adsArticles.eq(adsIndex).insertAfter($(target+' article:last-of-type')).show();
        //             ++adsIndex;
        //         }
        //     }
        // }
        return self;
    };

    // insert tracking code for links
    this.setupTrackingLink = function () {
        var $articles = $('article');
        // for (var i = 0, length = $articles.length; i < length; i++) {
        //     var $article = $articles.eq(i);
        //     var target = generateLinkTrack($article);
        //     $article.find('> .cover a, > header h1 a').attr('href', target);
        // };

        var $relates = $('article ul.relate a');
        for (var i = 0, length = $relates.length; i < length; i++) {
            var $relate = $relates.eq(i);
            $relate.attr('href', $relate.attr('href') + '#relate-article');
        };

        var $inners = $('.inner-article a');
        for (var i = 0, length = $inners.length; i < length; i++) {
            var $inner = $inners.eq(i);
            $inner.attr('href',$inner.attr('href')+'#inner-article');
        };
    };
    /**
     * Hovering box display at an exact coordinate on screen
     **/
    this.showHoverBox = function (content, position, styles, action) {
        var $popup = $('#popup');

        if ($popup.length == 0) {
            $('body').append($('<div>', {
                id: 'popup'
            }));

            $popup = $('#popup');
        }

        $popup.html(content);
        if (position) {
            $popup.css({
                top: position.top + 'px',
                left: position.left + 'px'
            });
        }

        if (action) {
            action();
        }

        if (styles) {
            $popup.css(styles);
        }

        $popup.show();

    };

    this.hideHoverBox = function () {
        var $popup = $('#popup');
        $popup.empty().hide();
        $popup.unbind();
    };

    // // Setup Search box
    // this.setupSearchBox = function () {
    //     var $searchBox = $('#searchbox'),
    //         $searchInput = $searchBox.find('input[type="text"]');

    //     $searchInput.focus(function () {
    //         if ($searchInput.val() == 'Nhập nội dung cần tìm...') {
    //             $searchInput.val('');
    //         }
    //     }).blur(function () {
    //         if ($.trim($searchInput.val()) == '') {
    //             $searchInput.val('Nhập nội dung cần tìm...');
    //         }
    //     });

    //     $searchBox.submit(function () {
    //         var url = window.location.origin,
    //             keyword = $.trim($searchInput.val());
    //         if (keyword != '' && keyword != 'Nhập nội dung cần tìm...') {
    //             keyword = keyword.replace(/\s+/, "-");
    //             url += "/tim-kiem/" + encodeURIComponent(keyword) + '.html';
    //         }
    //         window.location.href = url;
    //         return false;
    //     });
    // };

    /*
    this.notification = function(icon, title, message, url) {
        var noti = $('#notification');
        if ($(noti).length == 0) {
            noti = $('<div>', {id:"notification"});
            $(noti).append('<a class="btnLink"><img src="" width="36" height="36" class="icon" /><h1></h1><p></p></a><a href="#close" class="btnClose">Đóng</a>');
            $('body').prepend(noti);
            $(noti).find('.btnClose').on('click', function(){
                $(noti).transition({
                    marginTop: '-56px'
                }, 200);
            });
        }

        $(noti).find('.btnLink').attr('href',url).attr('title', title);
        $(noti).find('img.icon').attr('src', icon);
        $(noti).find('h1').text(title);
        $(noti).find('p').text(message);
        $(noti).transition({ marginTop: '0px'}, 500);
    };
    */

    /**
     * Toolbox display utilities link on page, such as contact info
     */
    this.setupToolbox = function () {
        $toolbox = $('#toolbox');
        $btnToTop = $toolbox.find('li.toTop a');
        $btnEmail = $toolbox.find('li.email a');
        $btnPhone = $toolbox.find('li.phone a');

        $(window).bind('scrollstop', function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > 200) {
                $btnToTop.stop().fadeIn();

                $('.btnToTop').css('display', 'block');

                if (scrollTop > 400 && page.article.getArticleType() != null && !$('#pushnotification').hasClass('hidden') && !$('#pushnotification').is(':visible')) {
                    if(!$('body').hasClass('appview')){page.showBottomBar();}
                }

                self.navigationMenu.show();
                self.navigationMenu.updateCurrent(scrollTop);
            } else {
                self.navigationMenu.hide();
                $btnToTop.stop().fadeOut();
                $('#pushnotification .actions .btnToTop').hide();
            }
        });
        $btnToTop.on('click', function () {
            self.scrollTo();
            return false;
        });
        $btnEmail.on('click', function () {
            showEmailBox();
            return false;
        });
        $btnPhone.on('click', function () {
            showPhoneBox();
            return false;
        });
    };

    /**
     * Hidden scrolling mechanism
     */
    this.setupScrollbar = function (scrollElement) {
        var $scrollElement = $(scrollElement);
        if ($scrollElement.length > 0 && DEVICE.type == "desktop") {
            $scrollElement.mCustomScrollbar({
                scrollButtons: {
                    enable: false
                },
                theme: "dark",
                autoHideScrollbar: true,
                autoDraggerLength: false
            });
        }
    };



    /**
     * Timestamp format utilities, able to convert to friendly format such as "2 hours ago"
     */
    this.formatTime = function (timestring, options) {
        //console.log(timestring);
        var difference, days, hours, minutes, month, pretext;
        var date;

        if (parseInt(timestring)<10000) {
            date = new Date(timestring.replace(/-/g,'/').replace('+', ' +'));
        } else {
            date = new Date((parseInt(timestring)-25200)*1000);
        }

        pretext = options == null || options.prefix == null ? "" : options.prefix;
        difference = now() - date.getTime();


        var days = Math.floor(difference / 1000 / 60 / 60 / 24);
        difference -= days * 1000 * 60 * 60 * 24;
        var hours = Math.floor(difference / 1000 / 60 / 60);
        difference -= hours * 1000 * 60 * 60;
        var minutes = Math.floor(difference / 1000 / 60);
        difference -= minutes * 1000 * 60;

        if (options && options.friendly === true) {
            //console.log('friendly:'+timestring);
            if (days == 0 && hours == 0) {
                return pretext + minutes + " phút trước";
            } else if (days == 1) {
                return pretext + "Hôm qua, lúc " + date.getHours() + " giờ " + date.getMinutes() + ' phút';
            }
        }

        hours = ((date.getHours() < 10) ? "0" : "") + date.getHours();
        minutes = ((date.getMinutes() < 10) ? "0" : "") + date.getMinutes();
        days = ((date.getDate() < 10) ? "0" : "") + date.getDate();
        month = ((date.getMonth() < 9) ? "0" : "") + (date.getMonth() + 1);

        return pretext + " " + hours + ":" + minutes + " ngày " + days + "/" + month + "/" + date.getFullYear();
    };

    /**
     * Bookmarking mechanism
     */
    this.addBookmark = function () {
        if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(document.title, window.location.href, '');
        } else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite
            window.external.AddFavorite(location.href, document.title);
        } else if (window.opera && window.print) { // Opera Hotlist
            this.title = document.title;
            return true;
        } else { // webkit - safari/chrome
            alert('Vui lòng bấm tổ hợp phím ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D để lưu trang.');
        }
    };

    /**
     * Provide mechanism to popup modal dialog requesting user input
     */
    this.showDialog = function (title, content, actions) {
        if (content == null) {
            return;
        }

        var $dialog = $('#dialog');

        if ($dialog.length == 0) {
            $('body').append($('<div>', {
                id: 'dialog'
            }));

            $dialog = $('#dialog');

            var dialogHtml = '<div>' +
                '<div class="header"></div>' +
                '<div class="content"></div>' +
                '<div class="action"><button class="btnSubmit">Đồng ý</button><button class="btnCancel">Đóng</button></div>' +
                '</div>';

            $dialog.html(dialogHtml);
        }

        var $btnSubmit = $dialog.find('.action button.btnSubmit'),
            $btnCancel = $dialog.find('.action button.btnCancel');

        $dialog.find('.header').html(title || 'Thông báo');
        $dialog.find('.content').html(content);

        $btnCancel.text('Đóng');

        if (actions != null) {
            if (actions.submit != null) {
                $btnSubmit.html(actions.submit.text || 'Đồng ý');

                $btnSubmit.on('click', function () {
                    actions.submit.action();
                }).show();
            } else {
                $btnSubmit.hide();
            }
            if (actions.cancel != null) {
                if (actions.cancel.text != null) {
                    $btnCancel.html(actions.cancel.text);
                }
            }
        }

        $btnCancel.on('click', function () {
            if (actions && actions.cancel && actions.cancel.action) {
                actions.cancel.action();
            }
            self.closeDialog();
        });

        $btnCancel.show();

        $dialog.find('> div').css({
            'margin-top': '-' + Math.round($('#dialog > div').height() / 2) + 'px'
        });

        $dialog.show();
    };
    this.closeDialog = function () {
        //console.log("close dialog");
        var $dialog = $('#dialog');
        $dialog.hide();
        $dialog.find('.header').empty();
        $dialog.find('.content').empty();
        $dialog.find('.action button').unbind('click').hide();
    };

    /**
     * Bottom bar display
     */
    this.showBottomBar = function () {
        if (DEVICE.screen != 'wide') {
            $('#pushnotification').css('bottom', '-50px');
            $('#pushnotification').show().transition({
                'bottom': '0px'
            });
        }

    };
    this.hideBottomBar = function () {
        if (DEVICE.screen == 'wide') {
            $('#pushnotification').hide();
        } else {
            $('#pushnotification').transition({
                'bottom': '-70px'
            }, 500, function () {
                $('#pushnotification').hide();
                $('#pushnotification').addClass('hidden');
            });

        }

    };

    /**
     * Provide mechanism to display small real time notification on the bottom right corner of the screen
     */
    this.pushNotification = function (content, action) {
        if ($('#popNotification').length == 0) {
            $('body').append($('<div>', {
                'id': 'popNotification'
            }).html('<div>'));
        }
        if (content == null) return;
        $('#popNotification > div').html(content);
        if (action) {
            $('#popNotification > div').bind('click', function () {
                action();
            });
        } else {
            $('#popNotification > div').bind('click', function () {
                self.hidePopNotification();
            });
        }
        $('#popNotification').fadeIn(500);
        /*
        $('#popNotification').show().transition({
            'right':'10px'
        });
        */
    };
    this.hidePushNotification = function () {
        /*
        $('#popNotification').transition({
            'right':'-160px'
        }, 500, function(){
            $('#popNotification > div').unbind().empty();
        });
        */
        $('#popNotification').fadeOut(400, function () {
            $('#popNotification > div').unbind().empty();
        });
    };

    this.showFollowDialog = function () {
        self.showDialog(
            'Quan tâm Zing News',
            '<p>Trở thành fan của Zing News trên Facebook để nhận tin hot nhất từ Zing News</p>' +
            '<div>' +
                '<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2FZingNews.VNG&amp;width=200&amp;height=62&amp;colorscheme=light&amp;show_faces=false&amp;header=false&amp;stream=false&amp;show_border=true&amp;appId=622829237762080" scrolling="no" frameborder="0" style="border:none;overflow:hidden;width:100%;height:70px;border:1px solid #ccc;border-radius:5px;margin-top:10px;" allowTransparency="true"></iframe>' +
            '</div>'
        );
    };

    /**
     * Mechanism to get current selected text
     */
    this.getSelection = function () {
        if (window.getSelection) {
            return window.getSelection();
        } else if (document.getSelection) {
            return document.getSelection();
        }
        return false;
    };

    /**
     * Mechanism to automatically attach article link when user copy text
     */
    this.insertCopy = function () {
        var body_element = document.getElementsByTagName('body')[0];
        var selection = self.getSelection();
        if (selection === false) return;
        if (selection.toString().length < 50) return;
        var pagelink = "<br /><br /> Bài viết: <a href='" + document.location.href + "' target='_blank'>" + document.location.href + "</a><br /><br /><a href='http://news.zing.vn' title='Zing News' target='_blank' style='display:block;font-size:0;line-height:0;'>Nguồn Zing News</a><br />";
        // change this if you want
        var copytext = selection + pagelink;
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        body_element.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {
            body_element.removeChild(newdiv);
        }, 0);
    };

    /**
     * Mechanism to display fullscreen any element
     */
    this.launchFullScreen = function (element) {
        //ga('send', 'event', 'Slideshow', 'Switch fullscreen', window.location.pathname);
        if (element.requestFullScreen) {
            element.requestFullScreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
        }
    };
    this.cancelFullscreen = function () {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
    };
    this.isFullScreen = function () {
        var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
        return (fullscreenElement != null);

    };
    this.isFullscreenEnable = function () {
        return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
    };

    /**
     * Scroll to top
     */
    this.scrollTo = function (pos) {
        var dest = pos || 0;
        $("html, body").animate({
            'scrollTop': dest + 'px'
        }, Math.abs($(window).scrollTop() - dest) / 5);
    };


    // this.getPageType = function () {
    //     if (cachedPageType) {
    //         return cachedPageType;
    //     }

    //     var pathname = window.location.pathname,
    //         pageType = '';

    //     if (pathname == '/' || pathname.search('index.html') > 0) {
    //         pageType = 'home';
    //     } else if (/-post[0-9]+\.html/i.test(pathname)) {
    //         pageType = 'article';
    //     } else if (/\/tag\/[^\.]*\.html/i.test(pathname)) {
    //         pageType = 'tag';
    //     } else if (/\/tim-kiem\/[^\.]*\.html/i.test(pathname)) {
    //         pageType = 'search';
    //     } else if (/\/tieu-diem\/[^\.]*\.html/i.test(pathname)) {
    //         pageType = 'topic';
    //     } else {
    //         pageType = 'category';
    //     }

    //     cachedPageType = pageType;

    //     return pageType;
    // };
}

/**
 * Article feature
 */
function Article() {
    var articles = $('article'),
        self = this,
        fullscreenSlideshow = new FullscreenSlideshow();

    this.commentEnabled = ($('#comments').length > 0);

    this.init = function () {
        if($('body#video').length>0) {

            Player.setupVideo();
        }
        self.renderArticle();
        self.renderArticleContent();
        self.renderSocialPlugins();
        self.setupRating();
        $('#attachments a').on('click',function(e){
            e.preventDefault();
            window.open($(this).attr('href'), $(this).text(), "height=600,width=800");
        });
        $('#metainfo .source a').on('click',function(e){
            e.preventDefault();
            var origin_title;

            page.showDialog(
                'Thông tin trích dẫn',
                '<p>Bài được Zing.vn đăng lại từ nội dung gốc theo liên kết bên dưới.</p>' +
                '<div style="font-weight:bold; font-size:1.1em;border: 1px solid #ccc;padding: 10px;margin-bottom: 10px;">'+$(this).text()+'</div>'
            );
        });
        return this;
    };

    this.getArticleType = function () {
        if ($('#video_content').length > 0) {
            return 'video';
        }
        var $content = $('#content');

        if ($content.length > 0) {
            return $content.hasClass('pictures_layout') ? 'picture' : 'text';
        }

        return null;
    };

    this.getArticleId = function () {
        // if (page.getPageType() == 'article') {
        //     return window.location.href.replace(window.location.hash, '').replace(/http.*-post|\.html#*/gi, '');
        // }
        return null;
    };

    this.getShortLink = function () {
        var shortURL;
        var articleId = self.getArticleId();
        if (articleId != null) {
            shortURL = 'http://news.zing.vn/zingnews-post' + articleId + '.html';
        } else {
            shortURL = window.location.href;
        }
        //console.log(shortURL);
        return shortURL;
    };

    // setup link for social
    this.renderSocialPlugins = function () {
        var article = {
            title: $('#content > header h1').html(),
            url: window.location.href.replace(window.location.hash, ''),
            summary: $('#content > header .summary p').html()
        };

        var $shareButtons = $('.share_buttons');
        $shareButtons.find('li a').on('click', function(e) {
            e.preventDefault();
            var $this = $(this),
                $parent = $this.parents('li'),
                url,
                newWindow;

            if ($parent.hasClass('btn_facebook')) {
                if (page.comment.FBAvailable) {
                    FB.ui({
                        method: 'feed',
                        link: article.url,
                        ref: 'InnerArticle'
                    });
                } else {
                    alert("Không truy cập được vào Facebook");
                }
            } else if ($parent.hasClass('btn_zingme')) {
                url = 'http://link.apps.zing.vn/share?u=' + encodeURIComponent(article.url) + '&t=' + encodeURIComponent(article.title) + '&desc=' + encodeURIComponent(article.summary);
                newWindow = window.open(url, "", 'width=500,height=300,scrollbars=no');
                if (window.focus) {
                    newWindow.focus();
                }
            } else if ($parent.hasClass('btn_google')) {
                url = 'https://plus.google.com/share?url=' + encodeURIComponent(article.url);
                newWindow = window.open(url, "", 'menubar=no,toolbar=no,resizable=yes,scrollbars=no,height=600,width=550');
                if (window.focus) {
                    newWindow.focus();
                }
            }
        });
    };

    // setup article links on the page, this include attach click tracking mechanism
    this.renderArticle = function () {

        // calculate if the article sidebar is height enough for its content, otherwise hide some section
        if (self.getArticleType() == 'text') {
            $(window).on('load', function () {
                var articleHeight = $('#content > article').height(),
                    sidebarHeight = $('#content > aside.sidebar').height();

                if (articleHeight < sidebarHeight + $('#content > .next_read').height() + 120) {
                    if (articleHeight < sidebarHeight) {
                        $('#content > aside.sidebar .topview').hide();
                    }
                } else {
                    $('#content > .next_read').show();
                    /*
                    if(page.device.browser=="chrome" && page.device.type=="desktop") {
                        new FloatingBox($('#content .sidebar .floating'), $('#content > .next_read'));
                    }
                    */
                }
            });
        }


    };

    /**
     * Format article content & setup tools
     */
    this.renderArticleContent = function () {
        var $content = $('article > .content');
        if ($content.length == 0) {
            return;
        }


        $('.inner-video a').on('click',function(e){
            e.stopPropagation();
            e.preventDefault();
            var videolink = $(this).attr('href')+'#singleplayer';

            if (DEVICE.type!='desktop') {
                var iframe = $('<iframe>',{'src':videolink}).css({'width':'100%', 'height':'100%'});
                $(this).parents('.inner-video').html(iframe);
            } else {
                var videowindow = window.open(videolink, "videoplayer", "width=600, height= 400, left=100, top=100, resizable=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no");
            }


        });

        $('.interactive-content a').on('click',function(e){
            e.preventDefault();
            var winWidth = parseInt($(this).attr('viewW'));
            var winHeight = parseInt($(this).attr('viewH'));
            var videowindow = window.open($(this).attr('href'), "interactive", "width="+winWidth+", height= "+winHeight+", left=300, top=300, resizable=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no");
        });

        // render toolbox (left side box) for article page
        var $pushNotification = $('#pushnotification');
        if ($pushNotification.length == 0) {
            //var fbLikeBox = "<div class='btnSocial'><div class='fb-like' data-href='" + self.getShortLink() + "' data-width='120' locale='en_US' data-layout='button_count' data-show-faces='false' data-share='false'></div></div>";
            //var ggLikeBox = "<div class='btnGoogle'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'>{lang: 'vi'}</script><div class='g-plus' data-action='share' data-annotation='bubble'></div></div>";
            //var ggLikeBox = '<div class="btnSocial"><div class="fb-share-button" data-href="'+ self.getShortLink() +'" data-type="icon_link"></div></div>';


            var likeBox = "<div class=\"btnSocial\"><div class=\"fb-like\" data-href=\""+ self.getShortLink() +"\" data-layout=\"box_count\" data-action=\"like\" data-show-faces=\"false\" data-share=\"true\"></div></div>";
            if (DEVICE.screen!='wide') {
                likeBox = "<div class='btnSocial'><div class='fb-like' data-href='" + self.getShortLink() + "' data-width='120' locale='en_US' data-layout='button_count' data-show-faces='false' data-share='false'></div></div>";
            }
            
            if (page.article.commentEnabled) {
                $pushNotification.find('.btnFacebook').on('click', function () {
                    page.scrollTo($('#comments').offset().top);
                    page.comment.renderComment();
                    $('#comments header li').removeClass('current');
                    $('#comments header li.facebook').addClass('current');
                    //ga('send', 'event', 'Comment', 'Jump to comment Facebook');
                    return false;
                });
            } else {
                $pushNotification.find('.btnFacebook').hide();
            }

        }

        // automatically insert article link on copy of text
        $content.bind('copy', function () {
            page.insertCopy();
            //ga('send', 'event', 'Article', 'Copy Text', window.location.pathname);
        });

        // grammar report mechanism activate when user select text
        $content.bind('mouseup', function (e) {
            var selectedText = page.getSelection();
            if (selectedText != false && selectedText != '') {
                page.showBottomBar();
                if ($pushNotification.find('.btnError').hasClass('active')) {
                    $pushNotification.find('.btnError').removeClass('active');
                } else {
                    $pushNotification.find('.btnError').addClass('active');
                }
            } else {
                $pushNotification.find('.btnError').removeClass('active');
            }
        });

        // clear all styles
        $content.find('*:not(".percent,.formatted")').removeClass("pBody").removeAttr("style");

        // reformat all table in content
        var tables = $content.find('> table');
        for (var i = 0, j = tables.length; i < j; i++) {
            $(tables[i]).attr('cellpadding', "0").attr('cellspacing', "0").removeAttr('height').removeAttr('width').removeAttr('align');
            // if the table has picture, auto reformat
            if ($(tables[i]).find('img').length != 0) {
                $(tables[i]).addClass('picture');
                $(tables[i]).find('td').each(function () {
                    if ($(this).find('img').length != 0) {
                        $(this).addClass('pic');
                    } else {
                        var text = $.trim($(this).text());
                        if (text == "" || text == "Nhập mô tả cho ảnh") $(this).remove();
                        else {
                            $(this).addClass('caption');
                        }
                    }
                });
                $(tables[i]).find('br').remove();
            }
        };

        // auto wrap textNode and clear empty nodes
        var textNode = $content.contents().filter(function () {
            return this.nodeType == 3;
        });
        for (var a = 0, b = textNode.length; a < b; a++) {
            if ($(textNode[a]).text() == "" || $(textNode[a]).text() == "\n") $(textNode[a]).remove();
            else {
                $(textNode[a]).wrap('<p>');
            }
        };

        // remove unncessary tags
        $content.find('> p ~ br').remove();
        $content.find('p > br + br').after('<span class="linebreak"></span>').remove();
        $content.find('> p').filter(function () {
            return ($(this).find('img').length == 0) && ($.trim($(this).text()) == "");
        }).remove();
        $content.find('> em').prev('p').css('display', 'inline');

        // Zooming/slideshow mechanism for image in article
        fullscreenSlideshow.init();

        if($('#content').hasClass('infographic_layout')) {
            var $infographics = $('.infographic_layout > article .picture img');
            var src;
            for(var i=0,j=$infographics.length; i<j; i++){
                var zoomer = $infographics[i];
                src = $(zoomer).attr('src');
                $(zoomer).after('<span class="zoom-instruct"></span>');

                //$(zoomer).attr('src',src.replace(/\/w\d+\//,'/w1024/'));
                $(zoomer).attr('data-zoom-image',src.replace(/\/w\d+\//,'/'));

                $(zoomer).ensureLoad(function(){
                    var originWidth = $(zoomer).width();
                    var originHeight = $(zoomer).height();
                    if(window.console) {
                        console.log('Original Loaded | '+originWidth + ":" + originHeight);
                    }
                    // if this is a vertical infographic that is long enough, don't do zoomer
                    if (originHeight/originWidth > 1.5) {
                        $(zoomer).siblings('.zoom-instruct').remove();
                        return;
                    }
                    var fullimg = $('<img>',{'src':src.replace(/\/w\d+\//,'/')}).ensureLoad(function(){
                        var fullWidth = $(fullimg).width();
                        var zoomtype = 'inner';
                        // depend on the size, decide which display method to use
                        if (fullWidth/originWidth>1.6) zoomtype = 'lens';
                        loadPlugin('elevateZoom', 'elevateZoom.js', function(){
                            log('Initialize zoom');
                            $(zoomer).siblings('.zoom-instruct').remove();
                            $(zoomer).elevateZoom({
                                responsive: true,
                                loadingIcon:true,
                                zoomType:zoomtype,
                                lensSize:'300',
                                cursor:'move',
                                loadingIcon:'http://stc.v3.news.zing.vn/css/img/icon_loading_small.gif'
                            });

                        });
                    });
                    $('body').append($(fullimg).hide());
                });
            }
        }
    };


    /**
     * Send user feedback on article content
     */
    this.reportError = function () {

        var selectedText = page.getSelection();
        if (selectedText == false || selectedText == null) {
            selectedText = "";
        }
        selectedText = $.trim(selectedText);

        var dialogMessage = '';
        if (selectedText.length > 0) {
            dialogMessage += '<p class="label">Nội dung chứa lỗi:</p>' +
                    '<blockquote class="error"><p>'+ selectedText +'</p></blockquote>' +
                    '<p class="label">Giải thích/sửa lỗi (không bắt buộc):</p>';
        } else {
            dialogMessage += '<p class="label">Nhập thông tin báo lỗi vào ô bên dưới</p>';
        }

        dialogMessage += '<div><textarea id="errorContent"></textarea></div>';

        page.showDialog(
            'Báo lỗi thông tin bài viết',
            dialogMessage, {
                submit: {
                    text: 'Gửi báo lỗi',
                    action: function () {
                        var errorContent = $.trim($('#errorContent').val());
                        if (errorContent.length > 0) {
                            var reportContent = '';
                            if (selectedText.length > 0) {
                                reportContent += "[Lỗi]\n" + selectedText + "\n";
                            }
                            reportContent += "[Sửa]\n" + errorContent;

                            $.ajax({
                                type: 'POST',
                                url: "http://news.zing.vn/api/grammarreport.aspx?id=" + page.article.getArticleId(),
                                cache: false,
                                data: {
                                    content: reportContent
                                }
                            }).done(function () {
                                ga('send', 'event', 'Article', 'Report Error', window.location.pathname);
                                //console.log($.cookie('grammar'));
                                page.closeDialog();
                                page.showDialog(
                                    'Báo lỗi thông tin bài viết',
                                    '<p>Cám ơn bạn đã báo lỗi bài này. Zing News sẽ cố gắng sửa nhanh nhất lỗi bạn đã báo. Bạn sẽ có thể báo lỗi bài này lại sau 24 tiếng.</p>'
                                );
                            });
                        } else {
                            page.closeDialog();
                            page.showDialog(
                                'Thông báo',
                                '<p>Để báo lỗi, bạn cần nhập nội dung có lỗi trong bài, hoặc chú thích thông tin bị sai của bài viết.</p>'
                            );
                        }

                    }
                }
            }
        );
    };

    /**
     * Setup rating  article
     */
    this.setupRating = function(){
        var ratinglist = page.storage.load('ratinglist');
        if (ratinglist!=null && ratinglist!==false && ratinglist.search(page.article.getArticleId())>=0) {
            return;
        }
        if (ratinglist==null || ratinglist===false) ratinglist="";

        $('#articleRating').show();
        $('#articleRating li').on('click',function(){
            var feedback=2,score=0;
            if ($(this).hasClass('ratingGood')) {
                feedback = 1; score=1;
            } else if ($(this).hasClass('ratingBad')) {
                feedback = 3; score = -1;
            }

            $.ajax({
                type : 'POST',
                cache : false,
                url : "http://news.zing.vn/api/rating.aspx?id=" + page.article.getArticleId() + "&value=" + feedback
            }).success(function() {
                ga('send', 'event', 'Article', 'Rating', window.location.pathname, score);
                // save the article id  so that we don't display message anymore
                if (feedback==3) {
                    $('#articleRating').html('<div class="result">Cám ơn bạn đã đánh giá. Ban biên tập đã được thông báo về ý kiến của bạn và sẽ cố gắng nâng cao chất lượng bài viết.</div>');
                } else {
                    $('#articleRating').html('<div class="result">Zing cám ơn bạn đã đánh giá và rất vui vì bài viết đã đem lại thông tin hữu ích cho bạn.<br /><a href="#share">Chia sẻ bài viết cho bạn bè</a></div>');
                    $('#articleRating .result a').on('click', function(e){
                        e.preventDefault;
                        if (page.comment.FBAvailable) {
                            FB.ui({
                                method: 'feed',
                                link: page.article.getShortLink(),
                                ref: 'InnerArticle'
                            });
                        } else {
                            alert("Không truy cập được vào Facebook");
                        }
                    });
                }
                ratinglist += page.article.getArticleId()+',';
                page.storage.insert('ratinglist',ratinglist);
            }).fail(function(){

            });

        });
    };
}




/**
 * Facebook intergration
 */
function SocialPlugin() {
    var self = this;
    this.FBAvailable = false;


    /**
     * Check if Facebook is accessible, then init
     */
    this.init = function () {
        jQuery.ajax({
            async: true,
            type: 'GET',
            url: '//connect.facebook.net/vi_VN/all.js#xfbml=1&appId=622829237762080',
            dataType: 'script',
            cache: true,
            data: null,
            complete: function (xhr, status) {
                if (xhr.status == 200) {
                    self.FBAvailable = true;
                    window.fbAsyncInit = function () {
                        log('Facebook init');
                        if (FB) {
                            FB.init({
                                appId: APP_ID,
                                logging: true,
                                status: true, // Check Facebook Login status
                                cookie: true
                            });


                            //self.setupSocialBox();
                            self.setupComment();
                            self.setupEvent();

                            // show follow button on toolbox
                            if ($('#toolbox .toTop').length > 0) {
                                $('#toolbox .toTop').after('<li class="facebook"><a href="javascript:page.showFollowDialog();" title="Quan tâm trên Facebook"><span>Facebook</span></a></li>');
                            }

                            FB.XFBML.parse();

                        }
                    };
                } else {
                    $('#pushnotification .btnFacebook').hide();
                    $('.fb-like').hide();
                    $('#comments').hide();
                }
            }

        });

    };

    // /**
    //  * Setup various Facebook plugins
    //  */
    // this.setupSocialBox = function () {
    //     if (DEVICE.screen == 'wide' && page.getPageType() == 'article' && $('body').attr('id')!='video' && $('#infographic').length<0) {
    //         $('body').append('<div class="fb-recommendations-bar" data-trigger="50%" data-site="news.zing.vn" data-num-recommendations="3" data-max-age="1" data-read-time="10" data-side="right" data-action="recommend"></div>');
    //         return;
    //     }
    //     if (page.getPageType() == 'home') {
    //         $('.sidebar #promotedposts').after(
    //             '<div class="fb-like-box" data-href="https://www.facebook.com/ZingNews.VNG" data-width="300" data-height="190" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false" style="float:left;margin-bottom:10px; border:1px solid #ccc;"></div>'

    //         );
    //         return;
    //     }

    // };

    /**
     * Setup comment box
     */
    this.setupComment = function () {
        //$('#socialpages').show();
        $('#comments').show();
        $('#pushnotification .actions .btnFacebook').show();
        if (page.article.commentEnabled && DEVICE.screen == 'wide') {
            self.getFacebookComment(page.article.getShortLink());
        }
        $('#comments #facebook').html('<div class="fb-comments" data-href="' + page.article.getShortLink() + '" data-colorscheme="light" data-numposts="10" data-width="660" data-notify="true" style="width:100%;"></div>').show();
    };

    /**
     * Subscribe to user interaction events, send feedback to server
     */
    this.setupEvent = function () {

        // comment event
        FB.Event.subscribe('comment.create', function (href, commentId) {
            if (page.article.getArticleId() == null) {
                //ga('send', 'event', 'Document', 'Comment Error: unidentified', window.location.pathname);
            } else {
                //ga('send', 'event', 'Document', 'Comment', window.location.pathname);
                log('Comment Created');
                // check if already rate the article
                var ratinglist = page.storage.load('ratinglist');
                // if already, just exit
                if (ratinglist!=null && ratinglist!==false && ratinglist.search(page.article.getArticleId())>=0) {
                    return;
                }
                if (ratinglist==null || ratinglist===false) ratinglist="";
                // else display dialog showing rating message
                page.showDialog(
                    'Phản hồi bài viết',
                    '<p>Bình luận của bạn đã được đăng! Để giúp Zing nâng cao chất lượng nội dung, bạn vui lòng cho biết đánh giá của bạn về nội dung bài viết:</p>'+
                    '<form>'+
                    '<p><label><input name="option" id="opt_good" type="radio" /> <strong>Rất tốt!</strong> Thông tin nhanh, nội dung trung thực và khách quan.</p>'+
                    '<p><label><input name="option" id="opt_normal" type="radio" /> <strong>Bình thường:</strong> Thông tin hữu ích, nội dung không lỗi.</p>'+
                    '<p><label><input name="option" id="opt_bad" type="radio" /> <strong>Kém:</strong> Nội dung không có giá trị, nhiều lỗi</p>'+
                    '</form>',
                    {
                        submit: {
                            text:'Gửi đánh giá',
                            action: function(){
                                var feedback = 2, score=0;
                                if ($('#opt_good').is(':checked')) {
                                    feedback = 1; score = 1;
                                } else if ($('#opt_bad').is(':checked')) {
                                    feedback = 3; score = -1;
                                }
                                $.ajax({
                                    type: 'POST',
                                    cache: false,
                                    url: "http://news.zing.vn/api/rating.aspx?id=" + page.article.getArticleId() + "&value="+feedback
                                }).success(function () {
                                    ga('send', 'event', 'Article', 'Rating', window.location.pathname, score);
                                    // save the article id  so that we don't display message anymore
                                });
                                page.closeDialog();
                            }
                        },
                        cancel: {
                            text:'Bỏ qua'
                        }

                    }
                );
                ratinglist += page.article.getArticleId()+',';
                page.storage.insert('ratinglist',ratinglist);

            }
            return true;
        });


    };

    /**
     * Get article's comment from Facebook
     */
    this.getFacebookComment = function (articleURL) {
        log('Get comment feed from Facebook');
        $.getJSON("https://graph.facebook.com/comments/?ids=" + articleURL, function (data) {
            var comments = data[articleURL].comments.data;
            if (comments.length > 0) {
                log("Article has more than 1 comment");
                self.showFacebookComment(comments);
            }
        });
    };

    /**
     * Show facebook comment in bubble
     */
    this.showFacebookComment = function (comments) {
        var counter = 0;
        var timer;

        // display next comment every 10 secs
        timer = setInterval(function () {
            //console.log(counter++);
            if (counter >= comments.length) {
                clearInterval(timer);
                return;
            }
            //ga('send', 'event', 'Comment', 'Show comment bubble',window.location.pathname);
            page.pushNotification(
                '<p class="author">' + comments[counter].from.name + '</p>' +
                '<div class="comment">' + comments[counter].message + '</div>',
                function () {
                    clearInterval(timer);
                    page.scrollTo($('#comments').offset().top);
                    $('#comments #facebook').show();
                    $('#comments header li').removeClass('current');
                    $('#comments header li.facebook').addClass('current');
                    page.hidePopNotification();
                    //ga('send', 'event', 'Comment', 'Click comment bubble');
                }
            );
            setTimeout(function () {
                page.hidePushNotification();
            }, 8000);
            counter++;
        }, 15000);

    };

}

function VideoPlayer() {
    var self=this;
    var frame_width = $('#video .player').width();
    var max_height = Math.round($(document).height()*0.6);
    var player_height = Math.round(frame_width*9/16);
    var cover_animation;
    if ($('#video.singleplayer').length>0) {
        player_height = $(document).height();
    } else if (player_height > max_height) {
        player_height = max_height;
        log('Exceed max height');
    }


    this.init = function(){

        // Setup preview video link
        if(window.location.hash.search('next_video')>=0) {
            $('#video_detail .player').append('<a href="javascript:Player.goBack();" class="btnPrev">Trước</a>');
        }

        // Setup next video link
        var nextVideo = $('#video_detail .btnNext');
        if(nextVideo.length>0) {
            $(nextVideo).attr('href', $(nextVideo).attr('href')+'#next_video');
        };

        // calculate video duration
        var $timedurations = $('article.video .duration');
        var secs;
        for(var i=0,j=$timedurations.length; i<j; i++){
            secs = parseInt($($timedurations[i]).text());
            if (secs>0) {
                var hr = Math.floor(secs / 3600);
                var min = Math.floor((secs - (hr * 3600))/60);
                var sec = secs - (hr * 3600) - (min * 60);

                if (hr==0) hr = ""; else hr += ":";
                if (min==0) min = ""; else min += ":";
                $($timedurations[i]).text( hr + min + sec);
            }
        };

        // Setup gif display mechanism
        var gifs = $('.cover[style*="_gif.jpg"]');
        $(gifs).parents('article').addClass('animated');
        $(gifs).mouseenter(function(){
            var self = this;
            $(this).append('<div id="circleG"><div id="circleG_1" class="circleG"></div><div id="circleG_2" class="circleG"></div><div id="circleG_3" class="circleG"></div></div>');

            // save the origin version
            var static_bg = $(self).attr('data-static');
            if (!static_bg) {
                static_bg = $(this).css('background-image').replace(/url\(|\)/g,'');
                $(this).attr('data-static',static_bg);
            }
            // get the animation version of cover
            var animate_bg = $(self).attr('data-gif');
            if (!animate_bg) {
                animate_bg = static_bg.replace('_gif.jpg','.gif');
                $(this).attr('data-gif',animate_bg);
            }
            // load the animation image
            var animation = $('<img>',{src:animate_bg,'class':'preloading'}).css({'width':'0px', 'height':'0px'}).ensureLoad(function(){
                //$(self).css('background-image', 'url('+animate_bg+')');
                $(self).append('<span class="animategif" style="background-image:url('+animate_bg+')"></span>');
                setTimeout(function(){
                    $('#circleG').remove();
                },500);
            });
            $('body').append(animation);
        }).mouseleave(function(){
            $('img.preloading').remove();
            //$(this).css('background-image','url('+$(this).attr('data-static')+')');
            $(this).find('.animategif').remove();
        });

        return self;
    };

    this.goBack = function(){
        if (document.referrer!="") {
            window.location.href = document.referrer;
        } else {
            history.go(-1);

            setTimeout(function(){
                self.goBack();
            },500);
        }
    };

    this.setupVideo = function() {
        var videourl = null;
        var videos = $('#content .content iframe[src*="youtube.com"],#content .content iframe[src*="tv.zing.vn"],#content .content iframe[src*="mp3.zing.vn"]');

        // get the video URL
        var $player = $('#video_detail .player > iframe');

        if ($player.length > 0) {
            videourl = $player.attr('src');
        } else {
            if (videos.length>0) {
                videourl = $(videos[0]).attr('src');
            }
        }

        if (videourl==null) return;

        if (videourl.search('tv.zing.vn')>=0 || videourl.search('mp3.zing.vn')>=0) {

            var videoid = videourl.match(/\/([^.^/]*)(\.html)*$/i)[1];
            if ($player.length>0) {
                $player.css({'width':'100%','height':player_height+'px','display':'block'});
            } else {
                $('#video_detail .player').append(videos[0]);
                $(videos[0]).css({'height':(player_height)+'px'} ).show();
            }

        } else if (videourl.search('youtube.com')>=0) {

            if(DEVICE.type=="desktop") {
                $('#video_detail .player').append('<video id="youtubeplayer" width="'+frame_width+'" height="'+player_height+'"><source src="'+videourl+'" type="video/youtube" ></video>').show();
                $('#youtubeplayer').mediaelementplayer({
                    iPhoneUseNativeControls: true,
                    AndroidUseNativeControls: true,
                    plugins: ['flash','silverlight']
                });
            } else {
                $('#video_detail .player').append(videos[0]);
                $(videos[0]).css({'height':(player_height)+'px'} ).show();
            }

        }

        return false;
    };

}